import React, { Fragment, useMemo, useState } from 'react';
import {
  FormStep,
  FormItem,
  Input,
  FormButtonGroup,
  Select,
  FormGrid,
  FormLayout,
  NumberPicker,
  ArrayItems,
  Space,
  Form,
  Editable,
} from '@formily/antd';
import { createForm } from '@formily/core';
import {
  FormProvider,
  FormConsumer,
  createSchemaField,
  observer,
} from '@formily/react';
import { Button, Drawer, message, ConfigProvider } from 'antd';
import 'antd/dist/antd.css';
import './index.less';
import ProTable from '@ant-design/pro-table';

import en_US from 'antd/es/locale-provider/en_US';
import DefaultTemplate from '@/components/Template/default';
import TemplateProTable from '@/components/TemplateProTable';
import CustomizeTemplate from '@/components/Template/customize';

const SchemaField = createSchemaField({
  components: {
    FormItem,
    FormStep,
    Input,
    Select,
    FormGrid,
    FormLayout,
    NumberPicker,
    ArrayItems,
    Space,
    Editable,
  },
});

const UniversalOption = [
  { label: '是', value: true },
  { label: '否', value: false },
];

// 本地化配置
const LocalOption = [
  { label: '中文', value: 'zh_cn' },
  { label: '英文', value: 'en_US' },
];

// 工具栏配置
const SettingOption = [
  { label: '全屏', value: 'fullScreen' },
  { label: '刷新', value: 'reload' },
  { label: '设置', value: 'setting' },
  { label: '密度', value: 'density' },
];

const FixedOption = [
  { label: '不固定', value: false },
  { label: '固定在右', value: 'right' },
  { label: '固定在左', value: 'left' },
];

const TableTypeOption = [
  { label: '默认版本 （啥都有）', value: 'default' },
  { label: '简单版本 （无表格工具栏）', value: 'Simple' },
  { label: '只读版本 （无下载上传编辑等操作）', value: 'readonly' },
  { label: '自定义', value: 'customize' },
];

const ValueOptions = [
  { value: `date`, label: `日期` },
  { value: `dateTime`, label: `日期时间` },
  { value: `dateWeek`, label: `周` },
  { value: `dateMonth`, label: `月` },
  { value: `dateQuarter`, label: `季度输入` },
  { value: `dateYear`, label: `年份输入` },
  {
    value: `dateRange`,
    label: `日期区间`,
  },
  {
    value: `dateTimeRange`,
    label: `日期时间区间`,
  },
  { value: `time`, label: `时间` },
  {
    value: `timeRange`,
    label: `时间区间`,
  },
  { value: `text`, label: `文本框` },
  { value: `select`, label: `下拉框` },
  { value: `digit`, label: `数字输入框` },
];

const form = createForm({
  initialValues: {
    headerTitle: '',
    table_type: 'default',
    usePage: true,
    manualRequest: false,
    action: ['add', 'import', 'export'],
    // cardProps: {
    //   title: '我是标题',
    // },
    local: 'en_US',
    pagination: {
      defaultPageSize: 20,
      showQuickJumper: true,
      size: 'default',
    },
    options: ['density', 'reload', 'setting', 'fullScreen'],
  },
});
const formStep = FormStep.createFormStep(1);

const schema = {
  type: 'object',
  properties: {
    step: {
      type: 'void',
      'x-component': 'FormStep',
      'x-component-props': {
        formStep: '{{formStep}}',
      },
      properties: {
        step1: {
          type: 'void',
          'x-component': 'FormStep.StepPane',
          'x-component-props': {
            title: '设置表格基本信息',
          },
          properties: {
            grid: {
              type: 'void',
              'x-component': 'FormLayout',
              'x-component-props': {
                // labelCol: 8,
                // wrapperCol: 10,
                layout: 'vertical',
                wrapperWidth: '800px',
                style: { maxWidth: 800, margin: '0 auto' },
                // layout: ['vertical', 'horizontal'],
                // labelAlign: ['left', 'right'],
                // labelCol: [24, 6],
                // wrapperCol: [24, 10],
                // breakpoints: [880]
              },
              properties: {
                'cardProps.title': {
                  type: 'string',
                  title: '标题',
                  required: true,
                  'x-decorator': 'FormItem',
                  'x-component': 'Input',
                },
                usePage: {
                  type: 'string',
                  title: '是否翻页',
                  required: true,
                  'x-decorator': 'FormItem',
                  'x-component': 'Select',
                  enum: UniversalOption,
                },
                grid: {
                  type: 'void',
                  'x-component': 'FormGrid',
                  'x-reactions': {
                    dependencies: ['usePage'],
                    fulfill: {
                      state: {
                        visible: '{{$deps[0]}}',
                      },
                    },
                  },
                  'x-component-props': {
                    // minColumns: [6, 4, 10],
                    // minWidth: 200,
                    // minColumns: 1
                  },
                  properties: {
                    'pagination.defaultPageSize': {
                      type: 'string',
                      title: '每页条数',
                      required: true,
                      'x-decorator': 'FormItem',
                      'x-component': 'NumberPicker',
                    },
                    'pagination.showQuickJumper': {
                      type: 'string',
                      title: '支持快速跳转',
                      required: true,
                      'x-decorator': 'FormItem',
                      'x-component': 'Select',
                      enum: UniversalOption,
                      width: 100,
                    },
                    // 'pagination.pageSizeOptions': {
                    //   type: 'string',
                    //   title: '分页可选数量',
                    //   required: true,
                    //   'x-decorator': 'FormItem',
                    //   'x-component': 'Select',
                    //   'x-decorator-props': { gridSpan: 2 },
                    //   'x-component-props': {
                    //     mode: 'multiple',
                    //     defaultValue: [10, 20, 50, 100]
                    //   },
                    //   enum: [10, 20, 50, 100]
                    // },
                    'pagination.size': {
                      type: 'string',
                      title: '尺寸',
                      required: true,
                      'x-decorator': 'FormItem',
                      'x-component': 'Select',
                      enum: ['small', 'default'],
                    },
                  },
                },
                local: {
                  type: 'string',
                  title: '国际化',
                  required: true,
                  'x-decorator': 'FormItem',
                  'x-component': 'Select',
                  enum: LocalOption,
                },
                table_type: {
                  type: 'string',
                  title: '表格模板',
                  required: true,
                  'x-decorator': 'FormItem',
                  'x-component': 'Select',
                  enum: TableTypeOption,
                },
                options: {
                  type: 'string',
                  title: 'table 工具栏',
                  required: true,
                  'x-decorator': 'FormItem',
                  'x-component': 'Select',
                  enum: SettingOption,
                  'x-component-props': {
                    mode: 'multiple',
                    value: ['density', 'reload', 'setting'],
                  },
                },
              },
            },
          },
        },
        step2: {
          type: 'void',
          'x-component': 'FormStep.StepPane',
          'x-component-props': {
            title: '设置表格列信息',
          },
          properties: {
            columns: {
              type: 'array',
              'x-component': 'ArrayItems',
              'x-decorator': 'FormItem',
              // title: '对象数组',
              items: {
                type: 'object', // NOTE: 不设置object Array 无效  | 创建实例
                properties: {
                  layout: {
                    type: 'void',
                    'x-component': 'FormLayout',
                    'x-component-props': {
                      // labelCol: 8,
                      // wrapperCol: 10,
                      // wrap: true
                      layout: 'vertical',
                    },
                    properties: {
                      space: {
                        type: 'void',
                        'x-component': 'Space',
                        'x-component-props': {
                          align: 'end',
                          wrap: true,
                        },
                        properties: {
                          sort: {
                            type: 'void',
                            'x-decorator': 'FormItem',
                            'x-component': 'ArrayItems.SortHandle',
                          },
                          title: {
                            type: 'string',
                            title: '标题',
                            'x-decorator': 'FormItem',
                            'x-component': 'Input',
                            'x-validator': [
                              {
                                required: true,
                                max: 10,
                              },
                            ],
                          },
                          dataIndex: {
                            type: 'string',
                            title: 'key',
                            'x-decorator': 'FormItem',
                            'x-decorator-props': {
                              tooltip: '数据字段名 不可重复',
                            },
                            'x-component': 'Input',
                            'x-validator': [
                              {
                                required: true,
                                max: 20,
                              },
                            ],
                          },
                          valueType: {
                            type: 'string',
                            title: '类型',
                            'x-decorator': 'FormItem',
                            'x-component': 'Select',
                            enum: ValueOptions,
                            required: true,
                            'x-decorator-props': {
                              tooltip: '这里关系到表单',
                            },
                            'x-component-props': {
                              style: {
                                width: 120,
                              },
                            },
                          },
                          selectEnum: {
                            type: 'string',
                            title: '配置选项',
                            'x-decorator': 'FormItem',
                            'x-component-props': {
                              style: {
                                width: 120,
                              },
                            },
                            // 'x-validator': [
                            //   {
                            //     required: true
                            //   },
                            // ],
                            'x-component': 'Input',
                            'x-decorator-props': {
                              tooltip:
                                "格式 [{ label: 'test', value: 'test' }]",
                            },
                            'x-reactions': {
                              dependencies: ['.valueType'], // 获取当前列的属性
                              fulfill: {
                                state: {
                                  visible: "{{$deps[0] === 'select'}}",
                                },
                              },
                            },
                            // enum: UniversalOption,
                          },
                          hideInSearch: {
                            type: 'string',
                            title: '隐藏搜索',
                            'x-decorator': 'FormItem',
                            'x-component-props': {
                              style: {
                                width: 120,
                              },
                            },
                            'x-component': 'Select',
                            enum: UniversalOption,
                          },
                          ellipsis: {
                            title: '超长省略',
                            'x-decorator': 'FormItem',
                            'x-component': 'Select',
                            enum: UniversalOption,
                            'x-component-props': {
                              style: {
                                width: 120,
                              },
                            },
                          },
                          fixed: {
                            type: 'string',
                            title: '是否固定',
                            'x-decorator': 'FormItem',
                            'x-component': 'Select',
                            'x-component-props': {
                              style: {
                                width: 120,
                              },
                            },
                            enum: FixedOption,
                          },
                          iobject: {
                            type: 'void',
                            title: '更多配置',
                            'x-component': 'Editable.Popover',
                            'x-component-props': {
                              arrowPointAtCenter: true,
                            },
                            properties: {
                              tooltip: {
                                type: 'string',
                                title: '提示内容',
                                'x-decorator': 'FormItem',
                                'x-component': 'Input',
                                'x-decorator-props': {
                                  tooltip: '就和这个一样',
                                },
                                maxLength: 255,
                              },
                              copyable: {
                                type: 'string',
                                title: '快捷复制',
                                'x-decorator': 'FormItem',
                                'x-component': 'Select',
                                enum: UniversalOption,
                              },
                            },
                          },
                          // NOTE: 如果有更多项，不方便换行可以尝试 Editable.Popover
                          remove: {
                            type: 'void',
                            'x-decorator': 'FormItem',
                            'x-component': 'ArrayItems.Remove',
                          },
                          // NOTE: 抽空补一个复制按钮
                        },
                      },
                    },
                  },
                },
              },
              properties: {
                add: {
                  type: 'void',
                  title: '添加条目',
                  'x-component': 'ArrayItems.Addition',
                  'x-component-props': {
                    defaultValue: {
                      valueType: 'text',
                      fixed: false,
                      ellipsis: true,
                      hideInSearch: false,
                      copyable: false,
                    },
                  },
                },
              },
            },
          },
        },
      },
    },
  },
};

const dataSource = [
  {
    key: '1',
    name: '胡彦斌',
    age: 32,
    address: '西湖区湖底公园1号',
  },
  {
    key: '2',
    name: '胡彦祖',
    age: 42,
    address: '西湖区湖底公园1号',
  },
];

// const columns = [
//   {
//     title: '姓名',
//     dataIndex: 'name',
//     key: 'name',
//   },
//   {
//     title: '年龄',
//     dataIndex: 'age',
//     key: 'age',
//   },
//   {
//     title: '住址',
//     dataIndex: 'address',
//     key: 'address',
//   },
// ];

export default () => {
  const [columns, setColumns] = useState([]);
  const [tableProps, setTableProps] = useState<any>({});
  const [visible, setVisible] = useState(false);

  const [template, setTemplate] = useState('default');

  return (
    <div className="wrapper_content">
      <div style={{ width: '80%', margin: '0 auto' }}>
        <FormProvider form={form}>
          <SchemaField schema={schema} scope={{ formStep }} />
          <FormConsumer>
            {() => (
              <FormButtonGroup align="center">
                <Button
                  disabled={!formStep.allowBack}
                  onClick={() => {
                    formStep.back();
                  }}
                >
                  上一步
                </Button>
                <Button
                  disabled={!formStep.allowNext}
                  onClick={() => {
                    formStep.next();
                  }}
                >
                  下一步
                </Button>
                <Button
                  disabled={formStep.allowNext}
                  onClick={() => {
                    formStep.submit((value) => {
                      console.log(value);

                      if (value.columns.length) {
                        // const { options } = value;

                        setTableProps({
                          ...value,
                          // options: options.length ? options.map() : false
                        });
                        setVisible(true);
                      } else {
                        message.error('最少也得加一条数据吧');
                      }
                    });
                  }}
                >
                  提交并预览
                </Button>
              </FormButtonGroup>
            )}
          </FormConsumer>
        </FormProvider>

        {/* 预览部分 */}
        <Drawer
          visible={visible}
          width="80%"
          title="预览"
          onClose={() => setVisible(false)}
        >
          <Select
            placeholder="选择样式模板"
            defaultValue="default"
            style={{ minWidth: '200px' }}
            options={[
              { label: '默认模板', value: 'default' },
              { label: '自定义模板', value: 'customize' },
              // { label: '默认模板', value: 'default' },
            ]}
            onChange={setTemplate}
          />
          {template === 'default' ? (
            <DefaultTemplate {...tableProps} />
          ) : (
            <CustomizeTemplate {...tableProps} />
          )}
        </Drawer>
      </div>
    </div>
  );
};
